package agend.client.behaviours;

import jade.core.behaviours.Behaviour;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;

import java.util.List;

import myContacts.Contact;
import myContacts.Email;
import agend.client.gui.utils.Broker;
import agend.client.gui.utils.HandlerView;
import agend.client.utils.GetAID;

public class SyncEmailBehaviour extends Behaviour{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private int step;
	List<String> services;

	public SyncEmailBehaviour() {
		super();
		step=0;
		services=new java.util.ArrayList<String>();
	}

	@Override
	public void action() {

				switch (step) {
		case 0:
		{
			DFAgentDescription template = new DFAgentDescription();

			ServiceDescription sd = new ServiceDescription();
			sd.setType("calendar-service");
			template.addServices(sd);
			try {
				DFAgentDescription[] result = DFService.search(myAgent, GetAID.df(), template, null);
				
				for (int i = 0; i < result.length; ++i) {
					services.add(result[i].getName().getLocalName().replace("#", "@"));	
				}
				step=1;
			}
			catch (FIPAException fe) {
				fe.printStackTrace();
				step=2;
			}


			break;
		}	
		case 1:
		{	

			System.out.println("Sto avviando il controllo");
			if(!services.isEmpty())
			{
				for(String service : services)
				{
					System.out.println("service: " + service);
					Email email=new Email();
					email.setAddress(service);
					//for(Contact contact: Broker.getAddressBookHandler().getContacts())
					for(Contact contact: Broker.getAddressBookHandler().getAddressBook().getContacts())
					{
						if(contact.getEmailAddresses().contains(email))
						{
							contact.setRegistered(true);
							int index=contact.getEmailAddresses().indexOf(email);
							contact.getEmailAddresses().get(index).setOn(true);
							System.out.println("AGGIORNATO");
						}
						
							
					}

				}

			}
			step=2;
			HandlerView.getBroker().notifyObserversAt(HandlerView.getMenupanel().getContactsPanel().getContactPanelBis(),Broker.getUsername());
			HandlerView.setMenuPanel();
			HandlerView.update();
			Broker.writeContacts();
			System.out.println("DONE!!!");
			break;
		}
		default:
			break;
		}



	}

	@Override
	public boolean done() {
		// TODO Auto-generated method stub
		return step==2;
	}

}
